<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="20%">
    <el-form ref="formRef" label-position="top" v-loading="formLoading" :model="formData" :rules="formRules"
      label-width="120">
      <el-form-item label="销售企业" prop="salesCompany">
        <el-select clearable filterable style="width: 100%" v-model="formData.salesCompany" placeholder="请选择销售企业">
          <el-option v-for="item in salesCompanyList" :key="item.id" :label="item.tenantName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="采购企业" prop="purchaseCompany">
        <el-select clearable filterable style="width: 100%" v-model="formData.purchaseCompany" placeholder="请选择采购企业">
          <el-option v-for="item in purchaseCompanyList" :key="item.id" :label="item.tenantName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="短倒价格" prop="shortPrice">
        <el-input :maxlength="20" v-model="formData.shortPrice" placeholder="请输入短倒价格" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
  import { cloneDeep } from 'lodash'
  import * as coalMarket from '@/api/coalMarket'
  import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'

  const emit = defineEmits(['success'])
  const dialogVisible = ref(false)
  const formLoading = ref(false)
  const message = useMessage()
  const dialogTitle = ref()
  const rowId = ref()
  const formRef = ref()
  const formData = ref({
    salesCompany: undefined,
    purchaseCompany: undefined,
    shortPrice: undefined,
  })
  const salesCompanyList = ref([])
  const purchaseCompanyList = ref([])

  const formRules = reactive({
    salesCompany: [{ required: true, message: '请选择销售企业', trigger: 'change' }],
    purchaseCompany: [{ required: true, message: '请选择采购企业', trigger: 'change' }],
    shortPrice: [{ required: true, message: '请输入短倒价格', trigger: 'blur' }],
  })

  const open = async (id) => {
    resetForm()
    dialogVisible.value = true
    rowId.value = id
    if (id) {
      dialogTitle.value = '编辑'
    } else {
      dialogTitle.value = '新增'
    }
    await getCompanyList()
    if (id) {
      getShortPriceSettingById(id)
    }
  }

  const resetForm = () => {
    Object.keys(formData.value).forEach(key => {
      formData.value[key] = undefined
    })
  }

  const getCompanyList = async () => {
    const res = await coalMarket.getCompanyList()
    const result = res || []
    salesCompanyList.value = result.filter(e => [2, 3].includes(e.companyAttribute))
    purchaseCompanyList.value = result.filter(e => [1, 3].includes(e.companyAttribute))
  }

  const getShortPriceSettingById = async (id) => {
    const res = await coalMarket.getShortPriceSettingById({ id })
    Object.keys(formData.value).forEach(key => {
      if ('salesCompany' === key) {
        formData.value[key] = salesCompanyList.value.find(e => {
          if (e.tenantId) {
            return e.tenantId === res.salesCompanyId && e.tenantName === res.salesCompanyName
          } else {
            return e.tenantName === res.salesCompanyName
          }
        })?.id
      } else if ('purchaseCompany' === key) {
        formData.value[key] = purchaseCompanyList.value.find(e => {
          if (e.tenantId) {
            return e.tenantId === res.purchaseCompanyId && e.tenantName === res.purchaseCompanyName
          } else {
            return e.tenantName === res.purchaseCompanyName
          }
        })?.id
      } else {
        formData.value[key] = res[key]
      }
    })
    console.log('formData.value', formData.value)
  }

  const submitForm = async () => {
    if (!formRef) return
    const valid = await formRef.value.validate()
    if (!valid) return
    formLoading.value = true
    if (rowId.value) {
      updateShortPriceSettingInfo()
    } else {
      createShortPriceSettingInfo()
    }
  }

  const createShortPriceSettingInfo = async () => {
    try {
      const data = cloneDeep(formData.value)
      data['salesCompanyId'] = salesCompanyList.value.find(e => e.id === data.salesCompany)?.tenantId
      data['salesCompanyName'] = salesCompanyList.value.find(e => e.id === data.salesCompany)?.tenantName
      data['purchaseCompanyId'] = purchaseCompanyList.value.find(e => e.id === data.purchaseCompany)?.tenantId
      data['purchaseCompanyName'] = purchaseCompanyList.value.find(e => e.id === data.purchaseCompany)?.tenantName
      delete data.colliery
      const res = await coalMarket.createShortPriceSettingInfo(data)
      if (res) {
        message.success('新增成功')
        emit('success')
        dialogVisible.value = false;
      }
    } finally {
      formLoading.value = false
    }
  }

  const updateShortPriceSettingInfo = async () => {
    try {
      const data = cloneDeep(formData.value)
      data['id'] = rowId.value
      data['salesCompanyId'] = salesCompanyList.value.find(e => e.id === data.salesCompany)?.tenantId
      data['salesCompanyName'] = salesCompanyList.value.find(e => e.id === data.salesCompany)?.tenantName
      data['purchaseCompanyId'] = purchaseCompanyList.value.find(e => e.id === data.purchaseCompany)?.tenantId
      data['purchaseCompanyName'] = purchaseCompanyList.value.find(e => e.id === data.purchaseCompany)?.tenantName
      delete data.colliery
      const res = await coalMarket.updateShortPriceSettingInfo(data)
      if (res) {
        message.success('编辑成功')
        emit('success')
        dialogVisible.value = false;
      }
    } finally {
      formLoading.value = false
    }
  }

  defineExpose({ open })
</script>